import store from '@/store'
import { Toast } from 'vant'
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: '/',
    redirect: '/main/menu'
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/Main.vue'),
    children: [
      {
        path: 'menu',
        name: 'menu',
        component: () => import('../views/Menu.vue'),
        meta: { index: 1 }
      },
      {
        path: 'order',
        name: 'order',
        component: () => import('../views/Order.vue'),
        meta: {
          index: 2,
          hasLogin: true
        }
      },
      {
        path: 'shopCart',
        name: 'shopCart',
        component: () => import('../views/ShopCart.vue'),
        meta: {
          index: 3,
          hasLogin: true
        }
      },
      {
        path: 'user',
        name: 'user',
        component: () => import('../views/User.vue'),
        meta: {
          index: 4,
          hasLogin: true
        },
      }
    ]
  },
  {
    path: '/searchFood',
    name: 'SearchFood',
    component: () => import('../views/SearchFood.vue'),
    meta: { index: 5 }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { index: 16 }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { index: 17 }
  },
  {
    path: '/foodDetail/:id',
    name: 'FoodDetail',
    component: () => import('../views/FoodDetail.vue'),
    meta: { index: 6 }
  },
  {
    path: '/checkOrder',
    name: "CheckOrder",
    component: () => import('../views/CheckOrder.vue'),
    meta: {
      index: 18,
      hasLogin: true
    }
  },
  {
    path: '/address',
    name: "Address",
    component: () => import('../views/Address.vue'),
    meta: {
      index: 19,
      hasLogin: true
    }
  },
  {
    path: '/addAddress',
    name: "AddAddress",
    component: () => import('../views/AddAddress.vue'),
    meta: {
      index: 20,
      hasLogin: true
    }
  },
  {
    path: '/editAddress',
    name: "EditAddress",
    component: () => import('../views/EditAddress.vue'),
    meta: {
      index: 20,
      hasLogin: true
    }
  },
  {
    path: '/chagePhoto',
    name: "ChagePgoto",
    component: () => import('../views/ChagePhoto.vue'),
    meta: {
      index: 30,
      hasLogin: true
    }
  },

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 前置守卫
router.beforeEach((to, from) => {
  if (to.meta.hasLogin === true) {
    if (!store.state.userInfo) {
      Toast('请先登录')
      // 把要去的目标地址保存起来
      return to.path = { path: '/login', query: { redirect: to.fullPath } }
    }
  }
})

export default router
